package cn.iocoder.an.module.business.service.auditplanarea;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.auditplandetail.vo.AuditPlanDetailRespVO;
import cn.iocoder.an.module.business.dal.dataobject.auditarea.AuditAreaDO;
import cn.iocoder.an.module.business.dal.dataobject.auditplandetail.AuditPlanDetailDO;
import cn.iocoder.an.module.business.dal.mysql.auditarea.AuditAreaMapper;
import cn.iocoder.an.module.business.dal.mysql.auditplandetail.AuditPlanDetailMapper;
import cn.iocoder.an.module.business.utils.WeComMessageUtil;
import cn.iocoder.an.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import cn.iocoder.an.module.business.controller.admin.auditplanarea.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.auditplanarea.AuditPlanAreaDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.auditplanarea.AuditPlanAreaMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 审核计划区域 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class AuditPlanAreaServiceImpl implements AuditPlanAreaService {

    @Resource
    private AuditPlanAreaMapper auditPlanAreaMapper;
    @Autowired
    private AuditPlanDetailMapper auditPlanDetailMapper;
    @Autowired
    private AuditAreaMapper auditAreaMapper;

    @Resource
    private AdminUserService userService;

    @Autowired
    private WeComMessageUtil weComMessageUtil;

    @Override
    public Long createAuditPlanArea(AuditPlanAreaSaveReqVO createReqVO) {
        // 插入
        AuditPlanAreaDO auditPlanArea = BeanUtils.toBean(createReqVO, AuditPlanAreaDO.class);
        auditPlanAreaMapper.insert(auditPlanArea);

        // 返回
        return auditPlanArea.getId();
    }

    @Override
    public void updateAuditPlanArea(AuditPlanAreaSaveReqVO updateReqVO) {
        // 校验存在
        validateAuditPlanAreaExists(updateReqVO.getId());
        // 更新
        AuditPlanAreaDO updateObj = BeanUtils.toBean(updateReqVO, AuditPlanAreaDO.class);
        //填报状态
        Integer writeStatus = updateReqVO.getWriteStatus();
        //部门

        Long areaId = updateObj.getAreaId();
        AuditAreaDO auditAreaDO = auditAreaMapper.selectById(areaId);
        Long deptId = auditAreaDO.getDeptId();
        String areaName = auditAreaDO.getDeptName();

        //审核项
        List<AuditPlanDetailRespVO> detailList = updateReqVO.getDetailList();
        detailList.forEach(detail -> {
           if (!"Y".equals(detail.getAuditResult()) && writeStatus == 2) {
               detail.setCompleteStatus(1);
               detail.setRepairDeptId(deptId);
               detail.setRepairDeptName(areaName);
               Long dutyUserId = detail.getDutyUserId();
               sendMessage(List.of(dutyUserId), areaName);
           }
        });
        List<AuditPlanDetailDO> detailDOList = BeanUtils.toBean(detailList, AuditPlanDetailDO.class);
        auditPlanDetailMapper.updateBatch(detailDOList);

        updateObj.setWriteTime(LocalDateTime.now());
        updateObj.setWriteUserId(SecurityFrameworkUtils.getLoginUserId());
        updateObj.setWriteUserName(SecurityFrameworkUtils.getLoginUserNickname());

        auditPlanAreaMapper.updateById(updateObj);
    }


    public void sendMessage(List<Long> dutyUserId,String deptName) {
        //推送消息
        List<AdminUserDO> userList = userService.getUserList(dutyUserId);
        String userIds = "";
        StringBuilder userIdBuilder = new StringBuilder();


        // 获取当前时间并格式化
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);

        for (AdminUserDO user : userList) {
            String userId = weComMessageUtil.getUserIdByMobile(user.getEnterpriseWeChatAccount());
            if (userId != null && !userId.trim().isEmpty()) {
                // 如果已经有内容了，先添加分隔符
                if (userIdBuilder.length() > 0) {
                    userIdBuilder.append("|");
                }
                userIdBuilder.append(userId);
            }
        }

        // 将 StringBuilder 转换为最终的字符串
        userIds = userIdBuilder.toString();
        // 可选：检查最终结果是否为空
        if (userIds.isEmpty()) {
            // 处理没有找到任何有效用户ID的情况
            System.out.printf("没有找到任何有效的企业微信 UserID");
            return;
        }

        // 1. 使用 sendTextMessage 方法 (更灵活，可以同时指定用户、部门、标签)

        String text = "您有新的分层审核问题追踪待处理,区域: " + deptName +",请注意";

        String systemMessage = text + formattedNow;
        // 将时间戳添加到消息中
        WeComMessageUtil.WeComSendResult weComSendResult = weComMessageUtil.sendTextMessage(systemMessage, userIds, null, null);
        System.out.printf("推送结果:" + weComSendResult.toString());

    }


    @Override
    public void deleteAuditPlanArea(Long id) {
        // 校验存在
        validateAuditPlanAreaExists(id);
        // 删除
        auditPlanAreaMapper.deleteById(id);
    }

    @Override
        public void deleteAuditPlanAreaListByIds(List<Long> ids) {
        // 删除
        auditPlanAreaMapper.deleteByIds(ids);
        }


    private void validateAuditPlanAreaExists(Long id) {
        if (auditPlanAreaMapper.selectById(id) == null) {
            throw exception(AUDIT_PLAN_AREA_NOT_EXISTS);
        }
    }

    @Override
    public AuditPlanAreaRespVO getAuditPlanArea(Long id) {
        AuditPlanAreaDO auditPlanAreaDO = auditPlanAreaMapper.selectById(id);

        AuditPlanAreaRespVO respVO = BeanUtils.toBean(auditPlanAreaDO, AuditPlanAreaRespVO.class);

        LambdaQueryWrapperX<AuditPlanDetailDO> queryWrapperX = new LambdaQueryWrapperX<>();
        queryWrapperX.eq(AuditPlanDetailDO::getPlanAreaId,id);
        List<AuditPlanDetailDO> detailDOList = auditPlanDetailMapper.selectList(queryWrapperX);
        List<AuditPlanDetailRespVO> detailList = BeanUtils.toBean(detailDOList, AuditPlanDetailRespVO.class);
        respVO.setDetailList(detailList);

        return respVO;
    }

    @Override
    public PageResult<AuditPlanAreaDO> getAuditPlanAreaPage(AuditPlanAreaPageReqVO pageReqVO) {
        //只查询我参与的

        return auditPlanAreaMapper.selectPage(pageReqVO);
    }

}